package com.gyx.lottery.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.gyx.lottery.common.errorcode.ServiceErrorCodeConstants;
import com.gyx.lottery.common.exception.ServiceException;
import com.gyx.lottery.common.utils.*;
import com.gyx.lottery.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class VerificatinoCodeImpl implements VerificationCodeService {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    SMSUtil smsUtil;
    private static final String VERIFICATINO_CODE_PREFIX="VERIFICATION_CODE_";
    private static final Long VERIFICATION_TIMEOUT = 60L;
    private static final String VERFICATION_CODE_TEMPLATE = "SMS_474175139";
    @Override
    public void sendVerificationCode(String phoneNumber) {
        //校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ILLEGAL);
        }
        //获取验证码
        String code = CaptchUtil.getCaptch(4);
        Map<String,String>map=new HashMap<>();
        map.put("code",code);
        //发送验证码，并保存到缓存当中去
        smsUtil.sendMessage(VERFICATION_CODE_TEMPLATE,phoneNumber, JacksonUtil.writeVauleAsString(map));
        redisUtil.set(VERIFICATINO_CODE_PREFIX+phoneNumber,code,VERIFICATION_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ILLEGAL);
        }
        //从缓存中取验证码
        return redisUtil.get(VERIFICATINO_CODE_PREFIX+phoneNumber);
    }
}
